<template>
    <div class="layout">
        <div class="container">

            <div class="header">
                <!-- 个人信息 -->
                <div class="left">
                    <img class="userImg" :src="props.user.img" alt="" />
                    <div class="userName">{{ props.user.userName }}</div>
                </div>
                <!-- 返回按钮 -->
            </div>
            <div class="gridcontainer">
                <!-- 图片 -->
                <div class="swiper">
                    <img v-if="cover" @click="clickImg" :src="cover" class="avatar cover" />
                    <el-upload class="avatar-uploader" :accept="acceptAstrict" :http-request="uploadFiles"
                        :before-upload="beforeUpload" :show-file-list="false" :disabled="cover.length > 0">
                        <img class="delete" @click="deleteCover" v-if="cover" src="/delete.svg" alt="">
                        <el-icon v-else class="avatar-uploader-icon">
                            上传封面
                        </el-icon>
                    </el-upload>
                </div>
                <!-- 内容和评论 -->
                <div class="main">
                    <div class="message">
                        <el-input class="title" v-model="title" style="font-size: calc(100vw * 24 / 1920);line-height: calc(100vw * 26/ 1920);" maxlength="20" placeholder="输入标题" />
                        <el-input
                            v-model="content"
                            style="width: 100%"
                            :rows="19"
                            type="textarea"
                            max-length="2000"
                            placeholder="Please input"
                        />
                        <el-button type="primary" @click="publish" :disabled="props.user.userName === '未登录'"
                            round>发帖</el-button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
const title = ref('')
const content = ref('')
const props = defineProps(['user'])
import axios from "axios";
const acceptAstrict = '.jpg,.jpeg,.png,.JPG,.PNG' //文件上传限制
const cover = ref('')

onMounted(() => {
    if (props.user.userName === '未登录') {
        ElMessage({
            message: "登陆后才可以发帖",
            offset: 100,
            type: 'error',
            duration: 5000
        })
    }
})

onUnmounted(() => {
    console.log('test');
    if(cover.value !== '') {
        deleteCover();
    }
})

const uploadFiles = function (file) {
    let formData = new FormData()
    formData.append('image', file.file)
    console.log(file.file)
    console.log(formData);
    axios({
        url: 'api/files/upload',
        method: 'POST',
        headers: {
            'Content-Type': 'multipart/form-data'
        },
        data: formData
    }).then(res => {
        console.log(res)
        cover.value = res.data.data;
    }).catch(e => {
        ElMessage({
            message: "服务器异常，请联系管理员B站诺丁汉小森林",
            type: "error"
        })
    })
}

//检查上传文件的格式
const beforeUpload = function (file) {
    if (file.size > 2 * 1024 * 1024) {
        alert('封面大小不要超过2MB')
        return false;
    }
    let fileType = file.type.substring(file.type.lastIndexOf('/') + 1)
    if (fileType !== 'jpeg' && fileType !== 'png') {
        alert('封面格式要求为jpg或png')
        return false;
    }
    return true
}

// 删除上传的图片
const deleteCover = function () {
    let img = cover.value.substring(cover.value.lastIndexOf('/') + 1)
    axios.post('/api/files/delete',{cover:img})
    .then(res => {
        if (res.data.code === 1) {
            ElMessage({
                message: "删除照片成功",
                offset: 300,
                type: 'success'
            })
            cover.value = ''
        } else {
            ElMessage({
                message: "删除照片失败",
                offset: 400,
                type: 'error'
            })
        }
    }).catch(e => {
        ElMessage({
            message: "服务器异常，请联系管理员",
            type: "error"
        })
    })
}

const clickImg = function () {
    ElMessage({
        message: "只允许上传一张图片",
        offset: 100,
        type: 'info'
    })
}

// 发布文章
const publish = function () {

    if (cover.value === '' || content.value === '' || title.value === '') {
        ElMessage({
            message: "封面,标题和内容不能为空",
            offset: 100,
            type: 'error'
        })
        return
    }
    const article = {
        title: title.value,
        cover: cover.value,
        content: content.value,
        uid: props.user.uid
    }
    axios.post('/api/articles', article, { headers: { 'token': localStorage.getItem('token') } })
        .then(res => {
            if (res.data.code === 1) {
                ElMessage({
                    message: "发帖成功！",
                    offset: 100,
                    type: 'success'
                })
                title.value = ''
                content.value = ''
                cover.value = ''
            } else {
                ElMessage({
                    message: "发布失败，请咨询管理员",
                    offset: 100,
                    type: 'error'
                })
            }
        }).catch(e => {
            ElMessage({
                message: "服务器异常，请联系管理员B站诺丁汉小森林",
                type: "error"
            })
        })
}

</script>

<style lang="scss" scoped>
.layout {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 200;
    margin-top: 5em;
    width: 100vw;
    height: 100vh;
}

.container {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

.header {
    width: 100%;
    height: 9%;
    background-color: #ccc;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    background-color: rgb(37, 34, 34);
    border-radius: 20px 20px 0 0;

    .left {
        position: relative;
        display: flex;
        align-items: center;
        flex-direction: row;
    }

    .userImg {
        width: calc(100vw * 60 / 1920);
        height: calc(100vw * 60 / 1920);
        border-radius: 60px;
    }

    .userName {
        margin-left: calc(100vw * 20 / 1920);
        font-size: calc(100vw * 24 / 1920); 
        color: rgb(161, 161, 161);
    }
}

.gridcontainer {
    height: 80%;
    width: 100%;
    background-color: #111;
    display: flex;

    .swiper {
        box-sizing: border-box;
        margin-left: 20px;
        width: 40%;
        height: 100%;
        position: relative;
        // background-color: #fff;
        display: flex;
        justify-content: center;
        align-items: center;

        .cover {
            width: 90%;
            height: 90%;
            border: 5px solid rgba(100, 100, 100, .5);
            border-radius: 30px;
            object-fit: contain;
        }

        .delete {
            position: relative;
            top: -150px;
            left: -25px;
            transition: all 0.5s;
            cursor: pointer;
        }

        .avatar-uploader .avatar {
            display: block;
        }

        .avatar-uploader .el-upload {
            border-radius: 6px;
            cursor: pointer;
            overflow: hidden;
            transition: var(--el-transition-duration-fast);
        }

        .avatar-uploader .el-upload:hover {
            border-color: var(--el-color-primary);
        }

        .avatar-uploader-icon {
            font-size: calc(100vw * 34 / 1920);
            color: #8c939d;
            width: calc(100vw * 100 / 1920);
            height: calc(100vw * 100 / 1920);
            border: 2px solid;
            border-radius:calc(100vw * 100 / 1920);
            overflow: hidden;
            text-align: center;
        }

        .delete:hover {
            transform: scale(1.2);
        }

    }

    .main {
        width: 60%;
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        margin-left: 20px;
    }
}

.layout {
    width: 99.9vw;
    height: 88.5vh;
    display: flex;
    justify-content: center;
    align-items: center;
}

.container {
    width: 60%;
}


.message {
    height: 90%;
    width: 95%;
    border: calc(100vw * 4 / 1920) solid #333;
    display: flex;
    flex-direction: column;
    overflow-x: hidden;
    overflow-y: scroll;
    .el-input {
        margin-bottom: calc(100vw * 3 / 1920);  
        font-size: calc(100vw * 16 / 1920);
        line-height: calc(100vw * 32/ 1920);
    }

    .title {
        width: 100%;
        height: 10%;
    }

    .content {
        width: 100%;
        height: 100%;
    }

    .el-button {
        margin-top: 6px;
        text-align: start;
        
    }
}

.message::-webkit-scrollbar {
    display: none;
}
</style>